package com.cnhis.drgs.core.util;

import com.cnhis.drgs.core.dao.mysql.MySqlPoolDbHelper;
import com.cnhis.drgs.core.xcode.ftl.FtlTemplate;
import com.cnhis.drgs.core.xcode.ftl.FtlTemplateUtil;
import com.cnhis.drgs.core.model.Column;
import com.cnhis.drgs.core.model.TableView;
import com.cnhis.drgs.util.Util;
import com.cnhis.drgs.vo.KeyValue;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class GeneratorUtil {


    /**
     *  基础类自动生成
     * @param map 要生成的表名
     * @param ip 数据库ip
     * @param port 端口号
     * @param schema 数据库名称
     * @param username 用户名
     * @param password 密码
     */
    public static void autoGenerator(Map<String, String> map, String ip,String port,String schema,String username,String password) {

        for (Map.Entry<String, String> entry : map.entrySet()) {

            String projectName = System.getProperty("user.dir").replace("\\", "\\\\");

            Class<?> clazz = null;

            try {
                //通过包名.类名获取类对象（因为该类在default包，所以可以不写包名）
                clazz = Class.forName(new Exception().getStackTrace()[1].getClassName());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            if (clazz == null) {
                System.err.println("获取项目包名称失败");
                return;
            }
            String basePackage = clazz.getPackage().getName();

            String moduleName = entry.getKey();

            boolean reserveSchema = false;

            Map<String, Object> items = Util.getSimpleMap(
                    new KeyValue<>("model", true),
                    new KeyValue<>("dao", true),
                    new KeyValue<>("mapper", true),
                    new KeyValue<>("service", true),
                    new KeyValue<>("serviceImpl", true),
                    new KeyValue<>("controller", true));

            GeneratorUtil.generator(ip, port, username, password, schema, entry.getValue(), projectName, basePackage, moduleName, reserveSchema, items);

        }

    }


    /**
     *  基础类自动生成 controller生成到指定模块下
     * @param map 要生成的表名
     * @param ip 数据库ip
     * @param port 端口号
     * @param schema 数据库名称
     * @param username 用户名
     * @param password 密码
     */
    public static void autoGenerator2(Map<String, String> map, String ip,String port,String schema,String username,String password) {

        for (Map.Entry<String, String> entry : map.entrySet()) {

            String projectName = System.getProperty("user.dir").replace("\\", "\\\\");

            Class<?> clazz = null;

            try {
                //通过包名.类名获取类对象（因为该类在default包，所以可以不写包名）
                clazz = Class.forName(new Exception().getStackTrace()[1].getClassName());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            if (clazz == null) {
                System.err.println("获取项目包名称失败");
                return;
            }
            String basePackage = clazz.getPackage().getName();

            String moduleName = entry.getKey();

            boolean reserveSchema = false;

            Map<String, Object> items = Util.getSimpleMap(
                    new KeyValue<>("model", true),
                    new KeyValue<>("dao", true),
                    new KeyValue<>("mapper", true),
                    new KeyValue<>("service", true),
                    new KeyValue<>("serviceImpl", true));

            GeneratorUtil.generator(ip, port, username, password, schema, entry.getValue(), projectName, basePackage, moduleName, reserveSchema, items);

            //指定controller生成的包路径
            projectName = "D:\\\\code\\\\drgs\\\\drgs-web";
            items = Util.getSimpleMap(new KeyValue<>("controller", true));
            GeneratorUtil.generator(ip, port, username, password, schema, entry.getValue(), projectName, basePackage, moduleName, reserveSchema, items);

        }

    }




    public static void generator(String ip, String port, String username, String password, String schema, String tableNames, String projectName, String basePackage, String moduleName, boolean reserveSchema, Map<String, Object> items) {

        Properties jdbcProperties = PropertiesUtil.loadProperties("/jdbc.properties");
        String url = String.format("jdbc:mysql://%s:%s/%s?autoReconnect=true&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%%2B8", ip, port, schema);
        jdbcProperties.put("url", url);
        jdbcProperties.put("username", username);
        jdbcProperties.put("password", password);
        MySqlPoolDbHelper dbHelper = new MySqlPoolDbHelper(DataSourceUtil.getDruidDataSource(jdbcProperties));

        for (String tableName : tableNames.split(",")) {

            TableView tableViewObject = dbHelper.getTableView(schema, tableName);
            if (tableViewObject == null) {
                System.err.println("警告：" + schema + "." + tableName + "不存在！！！");
                continue;
            }
            List<Column> columnList = dbHelper.getColumnList(schema, tableName);

            for (Map.Entry<String, Object> entry : items.entrySet()) {
                Boolean cover = (Boolean) entry.getValue();
                FtlTemplate template = FtlTemplateUtil.getFtlTemplate(entry.getKey(), projectName, basePackage, moduleName, reserveSchema, tableViewObject, columnList);
                File file = new File(template.getOutPutPath());
                if (cover || !file.exists()) {
                    template.outPutFile(file);
                    System.out.println("生成文件：" + file);
                } else {
                    System.out.println("忽略文件：" + file);
                }
            }
        }

    }


    /**
     * 删除指定表文件
     * @param map 表名
     */
    public static void autoRemove(Map<String,String> map) {

        String[] items =  new String[]{"model", "dao", "mapper", "service","serviceImpl","controller"};
        String projectName = System.getProperty("user.dir").replace("\\", "\\\\");

        Class<?> clazz = null;
        try {
            //通过包名.类名获取类对象（因为该类在default包，所以可以不写包名）
            clazz = Class.forName(new Exception().getStackTrace()[1].getClassName());
        } catch (ClassNotFoundException e) {
            System.err.println("获取项目包名失败");
            e.printStackTrace();
        }
        String basePackage = clazz.getPackage().getName();//项目包名

        for (Map.Entry<String, String> entry : map.entrySet()) {
            String moduleName = entry.getKey();
            String tableNames = entry.getValue();
            for (String tableName : tableNames.split(",")) {
                TableView tableView = new TableView();
                tableView.setTable_name(tableName);

                for (String item : items) {
                    FtlTemplate template = FtlTemplateUtil.getFtlTemplate(item, projectName, basePackage, moduleName, true, tableView, null);
                    File file = new File(template.getOutPutPath());
                    System.out.println("删除文件(" + (file.delete() ? "成功" : "失败") + ")：" + file);
                }

            }
        }
    }




    public static void remove(String tableNames, String projectName, String basePackage, String moduleName, String[] items) {

        for (String tableName : tableNames.split(",")) {

            TableView tableView = new TableView();
            tableView.setTable_name(tableName);

            for (String item : items) {
                FtlTemplate template = FtlTemplateUtil.getFtlTemplate(item, projectName, basePackage, moduleName, true, tableView, null);
                File file = new File(template.getOutPutPath());
                System.out.println("删除文件(" + (file.delete() ? "成功" : "失败") + ")：" + file);
            }

        }

    }
}
